package com.py.credit.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.transaction.annotation.Transactional;

import com.py.credit.constant.ResourcePath;
import com.py.credit.dao.EasyCreditApplicationDao;
import com.py.credit.entity.ApplicationEntity;
import com.py.credit.entity.AuthorizeModel;
import com.py.credit.entity.AuthorizeRecord;
import com.py.credit.entity.BranchEntity;
import com.py.credit.entity.EasyCreditLogEntity;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.entity.HireCodeEntity;
import com.py.credit.entity.HireEntity;
import com.py.credit.entity.HirePersonCodeEntity;
import com.py.credit.entity.HirePersonEntity;
import com.py.credit.entity.ReportCustom;
import com.py.credit.entity.SysMsgDetailEntity;
import com.py.credit.entity.SysMsgEntity;
import com.py.credit.service.AuthorizeModelService;
import com.py.credit.service.AuthorizeRecordService;
import com.py.credit.service.EasyCreditApplicationService;
import com.py.credit.service.GatewayUserService;
import com.py.credit.service.MsgService;
import com.py.credit.service.SysDictService;
import com.py.credit.utils.BarcodeUtil;
import com.py.credit.utils.QRcodeUtil;
import com.py.credit.utils.SQLBuilder;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;

@Service
public class EasyCreditApplicationServiceImpl implements EasyCreditApplicationService {

	@Autowired
	private EasyCreditApplicationDao easyCreditApplicationDao;

	@Autowired
	private SysDictService sysDictService;

	@Autowired
	private AuthorizeRecordService authorizeModelService;

	@Autowired
	private GatewayUserService gatewayUserService;

	@Autowired
	private MsgService msgService;

	@Override
	public void add(ApplicationEntity entity) {
		easyCreditApplicationDao.add(entity);
	}

	@Override
	public void modify(ApplicationEntity entity) {
		easyCreditApplicationDao.modify(entity);
	}

	@Override
	public List<Map> getOneModel() {
		return easyCreditApplicationDao.getOneModel();
	}

	@Override
	public List<ApplicationEntity> selectByConditionForPage(String name, String userType, List<String> columns,
			String[] additionalColumns, String conditionStr, Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		return easyCreditApplicationDao.selectByConditionForPage(name, userType, columns, additionalColumns, conditions,
				page);
	}

	@Override
	public List<ApplicationEntity> getOneInfo(String id, String name) {

		return easyCreditApplicationDao.getOneInfo(id, null);
	}

	@Override
	public List<Map> getBranchInfo(String ztmc, String applicationType, String batchId, Page page) {
		return easyCreditApplicationDao.getBranchInfoForPage(ztmc, applicationType, batchId, page);
	}

	@Override
	public void addBatch(String startTime, String endTime, String batchType, String productNum) {

		StringBuilder sb = new StringBuilder();
		SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMdd");
		Date date = new Date();
		Math.random();
		sb.append("M0").append(sdf.format(date)).append(String.valueOf(Math.round(Math.random() * 10)))
				.append(String.valueOf(Math.round(Math.random() * 10)))
				.append(String.valueOf(Math.round(Math.random() * 10)))
				.append(String.valueOf(Math.round(Math.random() * 10)));
		easyCreditApplicationDao.addBatch(sb.toString(), startTime, endTime, batchType, productNum);
	}

	@Override
	public void deleteBatch(List<String> batchId) {
		easyCreditApplicationDao.deleteBatch(batchId);
	}

	@Override
	public List<Map> selectBatch(String date, Page page) {
		return easyCreditApplicationDao.selectBatchForPage(date, page);
	}

	@Override
	public void addBranch(BranchEntity entity, ApplicationEntity applicationEntity, String dirpath, String url)
			throws Exception {
		String score = ""; // 调接口获取信用分
		String pass = "0";
		String branchId = UuidUtil.getUUid();
		SysMsgEntity msgEntity = new SysMsgEntity();
		List<SysMsgDetailEntity> detail = new ArrayList<>();
		SysMsgDetailEntity entity1 = new SysMsgDetailEntity();
		detail.add(entity1);
		entity1.setRevieverName(entity.getIsPass());
		entity1.setReviever(Long.valueOf(entity.getUserId()));
		entity1.setRevieveType(1);
		msgEntity.setMsgType(1);
		msgEntity.setDetails(detail);
		//
		if (("T").equals(entity.getId())) {// 如果接口没有查到分数则使用默认分数
			score = "0";
		} else {
			score = sysDictService.getDictDetails("MRXYF", "F").get(0).getDtlValue();
		}
		entity.setScore(score);
		entity.setId(branchId);
		if (("1").equals(applicationEntity.getIsAutoCheck())) {
//			if (applicationEntity.getLimitScore() <= Integer.parseInt(score)) {
//				if (("1").equals(entity.getApplicationType())) {
//					entity.setIsPass("1");
//					entity.setBatchId("1");
//					easyCreditApplicationDao.addBranch(entity);
//					dealTour(msgEntity, url, branchId, dirpath);
//					return;
//				}
//				if (("2").equals(entity.getApplicationType())) {
//					msgEntity.setMsgTitle("信易签审核通知");
//					msgEntity.setMsgContent("【信易加平台】您的信易签申请审核已通过！");
//					msgService.addMsgInfo(msgEntity);
//				}
//			} else {
//				pass = "2";
//				msgEntity.setMsgTitle(applicationEntity.getName() + "审核通知");
//				msgEntity.setMsgContent("【信易加平台】您的" + applicationEntity.getName() + "申请审核已驳回");
//				msgService.addMsgInfo(msgEntity);
//			}
		}
		entity.setIsPass(pass);
		entity.setBatchId("2");
		easyCreditApplicationDao.addBranch(entity);
	}

	@Override
	public void updateBranchInUse(String id) {
		easyCreditApplicationDao.updateBranchInUse(id);
	}

	@Override
	public void updateBranchInDel(List<String> id) {
		easyCreditApplicationDao.updateBranchInDel(id);
	}

	@Override
	public void updateBranchInPass(String isPass, String id) {
		easyCreditApplicationDao.updateBranchInPass(isPass, id);
	}

	@Override
	public String checkInUse(String id) {
		return easyCreditApplicationDao.checkInUse(id);
	}

	@Override
	@Transactional
	public void addHire(HireEntity entity, String userId) {
		easyCreditApplicationDao.addHire(entity);
		String infoId = entity.getId();
		easyCreditApplicationDao.addHirePerson(entity.getPerson(), infoId);
	}

	@Override
	@Transactional
	public void addLog(EasyCreditLogEntity entity, String url, String dirpath) throws Exception {
		GatewayUserEntity userEntity = gatewayUserService.getUserInfoById(entity.getUserId());
		SysMsgEntity msgEntity = new SysMsgEntity();
		List<SysMsgDetailEntity> detail = new ArrayList<>();
		SysMsgDetailEntity entity1 = new SysMsgDetailEntity();
		detail.add(entity1);
		entity1.setRevieverName(userEntity.getUsername());
		entity1.setReviever(userEntity.getId());
		entity1.setRevieveType(1);
		if (("1").equals(entity.getApplicationType())) {
			if (("1").equals(entity.getCheckStatus())) {
				msgEntity.setMsgTitle("信易加审核通知");
				msgEntity.setMsgContent("【信易加平台】您的信易游申请审核已通过！");
				dealTour(msgEntity, url, entity.getBranchId(), dirpath);
				return;
			} else {
				msgEntity.setMsgTitle("信易加审核通知");
				msgEntity.setMsgContent("【信易加平台】您的信易游申请审核已被驳回！");
			}
		} else if (("2").equals(entity.getApplicationType())) {
			if (("1").equals(entity.getCheckStatus())) {
				Map<String, Object> batch = easyCreditApplicationDao.selectBatch(entity.getBranchId());
				int score = (int) batch.get("score");
				if (score >= 700) {
					msgEntity.setMsgTitle("信易加审核通知");
					msgEntity.setMsgContent("【信易加平台】您的信易签申请审核已通过！");
					if (null != entity.getRecordNo()) {
						File file = new File(dirpath);
						if (!file.exists()) {
							file.mkdirs();
						}
						BarcodeUtil.generateFile(entity.getRecordNo(),
								dirpath + "/xyqbah_" + entity.getRecordNo() + ".png");
					}
				} else if (550 <= score && score < 700) {
					msgEntity.setMsgTitle("信易加审核通知");
					msgEntity.setMsgContent("【信易加平台】您的信易签申请审核需要到现场进行核对处理！");
					entity.setCheckStatus("3");
				}
			} else {
				msgEntity.setMsgTitle("信易加审核通知");
				msgEntity.setMsgContent("【信易加平台】您的信易签申请审核已被驳回！");
			}
		}
		msgEntity.setMsgType(1);
		msgEntity.setDetails(detail);

		msgService.addMsgInfo(msgEntity);
		easyCreditApplicationDao.updateBranchInPass(entity.getCheckStatus(), entity.getBranchId());
		easyCreditApplicationDao.addLog(entity);
		HireEntity hireEntity = new HireEntity();
		hireEntity.setRecordNo(entity.getRecordNo());
		hireEntity.setRecordNoPath(dirpath + "/xyqbah_" + entity.getRecordNo() + ".png");
		String id = (String) easyCreditApplicationDao.selectBatch(entity.getBranchId()).get("info_id");
		hireEntity.setId(id);
		easyCreditApplicationDao.updateHire(hireEntity);
		BranchEntity updateEntity = new BranchEntity();
		updateEntity.setPath(dirpath);
		updateEntity.setUserId(entity.getUserId());
		easyCreditApplicationDao.updateBranch(updateEntity);
	}

	@Override
	public HireEntity selectHire(String infoId) {
		HireEntity hireEntity = easyCreditApplicationDao.selectHire(infoId);
		hireEntity.setPerson(easyCreditApplicationDao.selectHirePerson(hireEntity.getId()));
		return hireEntity;
	}

	@Override
	public List<HireEntity> getHireForWeixin(String userId) {
		List<HireEntity> hireEntity = easyCreditApplicationDao.getHireForWeixin(userId);
		for (HireEntity hireEntity2 : hireEntity) {
			hireEntity2.setPerson(easyCreditApplicationDao.selectHirePerson(hireEntity2.getId()));
		}
		return hireEntity;
	}

	@Override
	public List<EasyCreditLogEntity> selectLog(Page page) {
		return easyCreditApplicationDao.selectLogForPage(page);
	}

	@Override
	public String checkInUseApp(String name) {
		return easyCreditApplicationDao.getOneInfo(null, name).get(0).getIsUse();
	}

	@Override
	public Integer getTourPassCount() {
		return easyCreditApplicationDao.getTourPassCount();
	}

	@Override
	public Integer getHirePassCount(String applicationType) {
		return easyCreditApplicationDao.getHirePassCount(applicationType);
	}

	@Override
	public void updateBatchIsUser(String id, String type) {
		easyCreditApplicationDao.updateBatchIsUser(id, type);
	}

	private void dealTour(SysMsgEntity msgEntity, String url, String branchId, String dirpath)
			throws IllegalStateException, IOException {
		BranchEntity entity = new BranchEntity();
		String token = UuidUtil.getUUid();
		// 拼接二维码地址
		StringBuilder sb = new StringBuilder();
		sb.append(url).append("?token=" + token).append("&id=" + branchId);
		// 获取二维码
		entity.setId(branchId);
		File file = QRcodeUtil.writeToFile(sb.toString(), 200, 200);
		FileInputStream in = new FileInputStream(file);
		MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
				IOUtils.toByteArray(in));
		gatewayUserService.fileUpload(multipartFile, dirpath, "code_");
		entity.setPath(dirpath + File.separator + "code_" + multipartFile.getOriginalFilename());
		String batchId = easyCreditApplicationDao.selectOneBatch();
		entity.setBatchId(batchId);
		msgEntity.setMsgTitle("信易游审核通知");
		msgEntity.setMsgContent("【信易加平台】您的信易游申请审核已通过");
		msgEntity.setLinkUrl(dirpath + File.separator + "code_" + multipartFile.getOriginalFilename());
		msgService.addMsgInfo(msgEntity);
		easyCreditApplicationDao.updateBranch(entity);
		if (!StringUtils.isEmpty(entity.getPath())) {
			AuthorizeRecord record = new AuthorizeRecord();
			record.setBranchId(branchId);
			record.setToken(token);
			authorizeModelService.addRecord(record);
		}
	}

	@Override
	public List<Map<String, Object>> getTokenDetail(String batchId, Page page) {
		return easyCreditApplicationDao.getTokenDetailForPage(batchId, page);
	}

	@Override
	public String selectOneBatch() {
		return easyCreditApplicationDao.selectOneBatch();
	}

	@Override
	public Map selectOneBranch(String id) {

		return easyCreditApplicationDao.selectBatch(id);
	}

	@Override
	public String getPhotoPath(String id) {
		return easyCreditApplicationDao.getHousePhotoPath(id);
	}

	@Override
	public String getPhotoPath(String pathName, String id, String Type) {
		return easyCreditApplicationDao.getCardPhotoPath(pathName, id, Type);
	}

	@Override
	public Map<String, Object> getUser(String userName) {
		return easyCreditApplicationDao.getUser(userName);
	}

	@Override
	public List<Map<String, Object>> getHistoryByPage(Page page, String id) {
		return easyCreditApplicationDao.getHistoryByPage(page, id);
	}

	@Override
	public int getHireCountByRecordNo(String recordNo) {
		int result = easyCreditApplicationDao.getHireCountByRecordNo(recordNo);
		return result;
	}

	@Override
	public void addReportConfig(String watermarker, CommonsMultipartFile reportWatermark) throws IOException {
		File dirPath = new File(watermarker);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}
		if (reportWatermark != null) {
			this.surePic(reportWatermark);
			reportWatermark.transferTo(new File(watermarker + ResourcePath.XYJ_WATERMAERK_NAME));
		}
		Map<String, Object> selectLatest = easyCreditApplicationDao.selectLatest();
		String path = watermarker + ResourcePath.XYJ_WATERMAERK_NAME;
		if (selectLatest != null) {
			int id = (int) selectLatest.get("id");
			easyCreditApplicationDao.updateByPrimaryKeySelective(id, path);
		} else {
			easyCreditApplicationDao.upload(path);
		}
	}

	private void surePic(CommonsMultipartFile waterMark) throws IOException {
		if (waterMark != null) {
			BufferedImage image = ImageIO.read

			(waterMark.getInputStream());
			if (image != null) {
				int width = image.getWidth();
				int height = image.getHeight();
				if (width > 1080 || height > 1920) {
					throw new ServiceException("图片图尺寸不超过1080*1920Px");
				}
			} else {
				throw new ServiceException("上传文件非图片,请重新上传");
			}
			if (!"image/png".equals(waterMark.getContentType()) && !"image/jpeg".equals(waterMark.getContentType())
					&& !"image/jpg".equals(waterMark.getContentType())) {
				throw new ServiceException("图片必须是JPG、JEPG、PNG 格式");
			}
			if (waterMark.getSize() > 3 * 1024 * 1024) {
				throw new ServiceException("图片不能超过3M");
			}
		}
	}

	@Override
	public Map<String, Object> getLatest() {
		return easyCreditApplicationDao.selectLatest();
	}

	@Override
	public boolean getHireByProve(String belongProveNumber, String hireStartTime, String hireEndTime) {
		boolean f = true;
		int i = easyCreditApplicationDao.getHireByProve(belongProveNumber, hireStartTime, hireEndTime);
		if (i > 0) {
			f = false;
		}
		return f;
	}

	@Override
	public void addQRCode(HireEntity entity, String dirPath) throws IllegalStateException, IOException {
		HireCodeEntity hcEntity = new HireCodeEntity();
		hcEntity.setId(entity.getId());
		String hireType = entity.getHireType();
		if("1".equals(hireType)) {
			hcEntity.setHireType(creditQECode("出租",dirPath));
		}else if("2".equals(hireType)) {
			hcEntity.setHireType(creditQECode("公房转租",dirPath));
		}else if("3".equals(hireType)) {
			hcEntity.setHireType(creditQECode("转租",dirPath));
		}
		hcEntity.setLocation(creditQECode(entity.getLocation(),dirPath));
		hcEntity.setLocationPart(creditQECode(entity.getLocationPart(),dirPath));
		String areaType = entity.getAreaType();
		if("1".equals(areaType)) {
			hcEntity.setAreaType(creditQECode("建筑面积",dirPath));
		}else if("2".equals(areaType)) {
			hcEntity.setAreaType(creditQECode("使用面积",dirPath));
		}else if("3".equals(areaType)) {
			hcEntity.setAreaType(creditQECode("居住面积",dirPath));
		}
		hcEntity.setHireArea(creditQECode(entity.getHireArea(),dirPath));
		hcEntity.setBelongProveType(creditQECode(entity.getBelongProveType(),dirPath));
		hcEntity.setBelongProveNumber(creditQECode(entity.getBelongProveNumber(),dirPath));
		hcEntity.setHireStartTime(creditQECode(entity.getHireStartTime(),dirPath));
		hcEntity.setHireEndTime(creditQECode(entity.getHireEndTime(),dirPath));
		hcEntity.setDeadline(creditQECode(entity.getDeadline(),dirPath));
		hcEntity.setHireMoney(creditQECode(entity.getHireMoney(),dirPath));
		hcEntity.setCommitMoney(creditQECode(entity.getCommitMoney(),dirPath));
		easyCreditApplicationDao.addHireCode(hcEntity);
		List<HirePersonCodeEntity> hpcEntityList = new ArrayList<>();
		for (HirePersonEntity hpEntity : entity.getPerson()) {
			HirePersonCodeEntity hpcEntity = new HirePersonCodeEntity();
			hpcEntity.setId(hpEntity.getId());
			String personType = hpEntity.getPersonType();
			if("1".equals(personType)) {
				hpcEntity.setPersonType(creditQECode("出（转）租人",dirPath));
			}else if("2".equals(personType)) {
				hpcEntity.setPersonType(creditQECode("出租代理人",dirPath));
			}else if("3".equals(personType)) {
				hpcEntity.setPersonType(creditQECode("承租人",dirPath));
			}else if("4".equals(personType)) {
				hpcEntity.setPersonType(creditQECode("承租代理人",dirPath));
			}else if("5".equals(personType)) {
				hpcEntity.setPersonType(creditQECode("居住使用人",dirPath));
			}
			hpcEntity.setName(creditQECode(hpEntity.getName(),dirPath));
			hpcEntity.setCardType(creditQECode(hpEntity.getCardType(),dirPath));
			hpcEntity.setCardNumber(creditQECode(hpEntity.getCardNumber(),dirPath));
			hpcEntity.setPhone(creditQECode(hpEntity.getPhone(),dirPath));
			hpcEntityList.add(hpcEntity);
		}
		easyCreditApplicationDao.addHirePersonCode(hpcEntityList,entity.getId());
	}
	
	private String creditQECode(String name,String dirPath) throws IOException {
		File file = QRcodeUtil.writeToFile(name, 200, 200);
		FileInputStream in = new FileInputStream(file);
		MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
				IOUtils.toByteArray(in));
		gatewayUserService.fileUpload(multipartFile, dirPath, "code_");
		return dirPath + File.separator + "code_" + multipartFile.getOriginalFilename();
	}
	
	@Override
	public String selectHireCode(String table, String type, String infoId) {
		String path = "";
		if("hire".equals(table)) {
			path = easyCreditApplicationDao.selectHireCode(type,infoId);
		}else if("person".equals(table)){
			path = easyCreditApplicationDao.selectHirePersonCode(type,infoId);
		}
		return path;
	}

	@Override
	public void addCases(String batchId, String xyjcp, String syztmc, String xydm, String ztlx, String tgdw,
			String xsyhnr, String fkdw, String fksj, long officeId, Long id) {
		easyCreditApplicationDao.addCases(batchId,xyjcp,syztmc,xydm,ztlx,tgdw,xsyhnr,fkdw,fksj,officeId,id);
		
	}


	
	@Override
	public List<Map<String, String>> selectCaseForPage(Page page, String type, String xyjcp) {
		
		return easyCreditApplicationDao.selectCaseForPage(page,type,xyjcp);
	}

	
	
	@Override
	public void deleteData(String id) {
		easyCreditApplicationDao.deleteData(id);
		
	}

	
	@Override
	public List<Map<String, String>> selectCaseDetail(String batchId) {
		
		return easyCreditApplicationDao.selectCaseDetail(batchId);
	}

	
	
	
	@Override
	public void deleteProduct(String id) {
		easyCreditApplicationDao.deleteProduct(id);
		
	}

	
	@Override
	public void updateData(String batch_id, String xyjcp, String syztmc, String xydm, String ztlx, String tgdw,String fksj) {
		easyCreditApplicationDao.updateData(batch_id,xyjcp,syztmc,xydm,ztlx,tgdw,fksj);
		
	}
}
